//引入样式
require("../../assets/css/reset.css")
require('../../assets/css/normalize.css')
require('../../assets/fonts/iconfont.css')

require('./sports_running.less');

//引入模块
const axios = require('../../utils/axios.js');
const dom = require('../../utils/dom.js');
const date = require('../../utils/date.js')
document.addEventListener("DOMContentLoaded", function () {
    let duration = 0;
    let calorie = 0;
    let meter = 0;
    let time = null;
    // 设置一个开始定时器
    function start() {
        time = setInterval(function () {
            meter += random(3, 7);
            dom.get('#totalMeter').textContent = (meter / 1000).toFixed(2);
            dom.get('#speed').textContent = random(3, 7) + '米/秒';
            dom.get('#time').textContent = date.getHMS(duration++);
            calorie = 55 * (meter / 1000) * 1.036;
            dom.get('#calorie').textContent = calorie.toFixed(2);
        }, 1000)
    };
    start();

    // 设置一个随机数函数
    function random(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }


    // 暂停
    dom.get('.pause').addEventListener('click', function () {
        dom.get('.pause').style.display = 'none';
        dom.get('.start').style.display = 'block';
        dom.get('.close').style.display = 'block';
        clearInterval(time); //清除定时器标识，停止计时
    });

    //继续
    dom.get('.start').addEventListener('click', function () {
        dom.get('.pause').style.display = 'block';
        dom.get('.start').style.display = 'none';
        dom.get('.close').style.display = 'none';
        start(); //继续执行定时器
    });

    //结束
    dom.get('.close').addEventListener('click', function () {
        //发请求保存数据
        axios.post('/api/exercise/save', {
            type: 0,
            duration,
            calorie,
            meter,
        }).then(res => {
            if (res.data.errno === 0) {
                alert('本次训练已结束');
                location.href = 'sports_run.html'
            }
        })
    });
})